// Learn TypeScript:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/typescript.html
//  - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/reference/attributes.html
//  - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/life-cycle-callbacks.html
//  - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/life-cycle-callbacks.html

import {wxUtils} from "../wx/wxUtils";
import {SocketUtils} from "../socket/SocketUtils";
import * as proto from "../socket/proto/proto";
import {model} from "../web/model/Model";
import {apiUtils} from "../web/api/ApiUtils";
import {SocketState} from "../socket/SocketIO";
import Menu from "../menu/menu";
import {Statistic} from "../../statistic/statistic";

const {ccclass, property} = cc._decorator;

@ccclass
export default class Loading extends cc.Component {

  @property(cc.ProgressBar)
  private loadingProgressBar: cc.ProgressBar = null;
  @property(cc.Label)
  private progressLabel: cc.Label = null;
  @property(cc.Node)
  private progressNode: cc.Node = null;
  @property(cc.Node)
  private authNode: cc.Node = null;

  private isAssetsLoaded = false;


  // LIFE-CYCLE CALLBACKS:

  private isAuth = false;
  private postData: any = null;

  async onLoad() {
    this.isAssetsLoaded = false;
    this.progressNode.x = -540;
    this.loadingProgressBar.progress = 0;
    this.progressLabel.string = `努力加载${0}%......`;
    this.authNode.active = false;

    cc.director.preloadScene('menu', (completedCount, totalCount) => {
      this.loadingProgressBar.progress = parseFloat((completedCount / totalCount).toFixed(2));
      this.progressLabel.string = `努力加载${parseInt(this.loadingProgressBar.progress * 100)}%......`;
      this.progressNode.x = -540 + 1020 * this.loadingProgressBar.progress;
    }, () => {
      this.isAssetsLoaded = true;
      this.onComplete();
      if (!this.isAuth) {
        this.progressNode.active = false;
        this.loadingProgressBar.node.active = false;
        this.progressLabel.node.active = false;
        this.authNode.active = true;
      }
    })
    let btn = null;
    wxUtils.login(async (postData) => {
      if (postData.code === -1) {
        this.isAuth = false;
        const sysInfo = await wxUtils.getSysInfo()
        btn = wx.createUserInfoButton({
          type: 'text',
          text: '',
          style: {
            left: 0,
            top: 0,
            width: sysInfo.screenWidth,
            height: sysInfo.screenHeight,
          }
        });
        btn.onTap(function (res) {
          wxUtils.reAuth(res.userInfo)
        });
      }
      //成功
      else {
        if (btn) {
          btn.destroy();
        }
        this.isAuth = true
        this.postData = postData;
        SocketUtils.getLogicSocket().connect(postData, this.onOpen.bind(this));
      }
    });
    Statistic.init();
  }

  private isOpen = false;

  onOpen(err) {
    if (err) {
      return;
    }
    if (this.postData) {
      apiUtils.uploadUserInfo(this.postData)
      SocketUtils.getLogicSocket().once(proto.UserAck, () => {
        this.isOpen = true
        this.onComplete();
      })
    }
    // SocketUtils.getLogicSocket().
  }

  onComplete() {
    if (this.isAssetsLoaded && this.isOpen) {
      SocketUtils.getLogicSocket().off(proto.UserAck, this.onComplete.bind(this))
      cc.director.loadScene('menu', () => {
        const menu = cc.director.getScene().getChildByName("menu").getComponent(Menu);
        // 七日好礼能领取或者七日过后每日签到未签到
        let showSeven = model.user.hasSevenLoginReward;
        let showDaily = (!model.user.sevenLoginValid && !model.user.isSignToday);
        if (showSeven || showDaily) {
          menu.showSign();
        }
      });
    }
  }

  private scaleAction() {
    const duration = 1;
    return cc.sequence(
      cc.scaleTo(duration * 0.3, 1.10, .85),
      cc.scaleTo(duration * 0.1, .85, 1.10),
      cc.scaleTo(duration * 0.1, 1.10, .85),
      cc.scaleTo(duration * 0.15, .95, 1.05),
      cc.scaleTo(duration * 0.1, 1.05, .95),
      cc.scaleTo(duration * 0.25, 1, 1),
      cc.delayTime(4)
    ).repeatForever();
  }

  start() {
    this.progressNode.runAction(this.scaleAction())
  }
}
